import { getCookieLanguage } from "./cookie"
import { isDate, isNumber, isString } from "./is"

interface ICalculateDuration {
  days: number
  hours: number
  minutes: number
  seconds: number
}

export function calcTimeDuration(start: any, end: any): boolean | ICalculateDuration {
  if (!start || !end) return false
  // 格式化， ios 不兼容 2024-10-10 这种格式
  if (isString(start)) {
    start = start.replace(/-/g, "/")
    start = new Date(start).getTime()
  }
  if (isString(end)) {
    end = end.replace(/-/g, "/")
    end = new Date(end).getTime()
  }
  // 计算相差的毫秒数
  let duration = end - start

  // 计算天数
  const days = Math.floor(duration / (1000 * 60 * 60 * 24))
  duration -= days * (1000 * 60 * 60 * 24)

  // 计算小时数
  const hours = Math.floor(duration / (1000 * 60 * 60))
  duration -= hours * (1000 * 60 * 60)

  // 计算分钟数
  const minutes = Math.floor(duration / (1000 * 60))
  duration -= minutes * (1000 * 60)

  // 计算秒数
  const seconds = Math.floor(duration / 1000)

  return { days, hours, minutes, seconds }
}

/* xx天xx小时xx分xx秒 */
export function formatDateDHMS(start: any, end: any) {
  const dateInfo = calcTimeDuration(start, end)

  if (dateInfo) {
    let result = ""
    const { days, hours, minutes, seconds } = dateInfo as ICalculateDuration
    if (days > 0) result += `${days}天`
    if (hours > 0) result += `${hours}小时`
    if (minutes > 0) result += `${minutes}分钟`
    if (seconds > 0) result += `${seconds}秒`
    return result
  }
  return ""
}

export function formatDateDHMSWithLocale(start: any, end: any, locale:any) {
  const { d = '天', h = '小时', m = '分钟', s = '秒' } = locale
  const dateInfo = calcTimeDuration(start, end)
  const lang = getCookieLanguage()
  
  if (dateInfo) {
    let result = ""
    const { days, hours, minutes, seconds } = dateInfo as ICalculateDuration
    if (days > 0) result += `${days}${lang === 'en_US' && days > 1 ? d+'s' : d}`
    if (hours > 0) result += ` ${hours}${lang === 'en_US' && hours > 1 ? h+'s' : h}`
    if (minutes > 0) result += ` ${minutes}${lang === 'en_US' && minutes > 1 ? m+'s' : m}`
    if (seconds > 0) result += ` ${seconds}${lang === 'en_US' && seconds > 1 ? s+'s' : s}`
    return result
  }
  return ""
}

